package com.jiazhong.mingxing.boot.boot11.事务消息;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

@Slf4j
public class 消息确认者 implements TransactionListener {
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("开始进入消息确认环节");
        // 获取到刚才添加的标签
        String keys = message.getKeys();
        return switch (keys) {
            case "NUM:1", "NUM:3", "NUM:5" -> {
                log.info("{}消息被确认了", keys);
                yield LocalTransactionState.COMMIT_MESSAGE;
            }
            case "NUM:2", "NUM:4", "NUM:6" -> {
                log.info("{}没有通过", keys);
                yield LocalTransactionState.ROLLBACK_MESSAGE;
            }
            case "NUM:7", "NUM:8", "NUM:9", "NUM:10" -> {
                log.info("{}还需要二次确认", keys);
                yield LocalTransactionState.UNKNOW;
            }
            default -> null;
        };

    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        log.info("我是二次确认者");
        String keys = messageExt.getKeys();
        if (keys.equals("NUM:7") || keys.equals("NUM:9")) {
            return LocalTransactionState.COMMIT_MESSAGE;
        } else if (keys.equals("NUM:8")) {
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
        return LocalTransactionState.UNKNOW;
    }
}
